﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Generic;

public partial class mystudy_multiFileUpLoad : System.Web.UI.Page
{
    public SqlCommand com;
    public SqlCommand com1;
    public string url = "";
    string playListFile = "";
    public string htmlName = "";
    public string xmlAndHtmlName = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> userList = Application.Get("GLOBAL_USER_LIST") as Dictionary<string, string>;
        if (userList != null)
        {
            foreach (var item in userList)
            {
                if (item.Key != null && String.Compare(item.Key, Session.SessionID) == 0)
                {
                    if (item.Value != null && String.Compare("useronline", item.Value) == 0)
                    {
                        userList.Remove(Session.SessionID);
                        Application.Lock();
                        Application.Add("GLOBAL_USER_LIST", userList);
                        Application.UnLock();
                        Response.Write("<script type='text/javascript'>alert('您的账号已经在其他地方登录,您被强制下线');window.location='../../logout_close.aspx';window.parent.opener.parent.location='../../index.aspx';window.parent.close();</script>");
                    }
                    break;
                }
            }
        }
        if (Session["sUserName"] == null)
        {
            Response.Write("<script language=javascript>alert('未登录或登录已到期，请返回登录页面重新登录！');window.parent.close();</script>");
            return;
        }
        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["gConnectionString"]);
        conn.Open();
        com = new SqlCommand();
        com.Connection = conn;
        SqlConnection conn1 = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["gConnectionString"]);
        conn1.Open();
        com1 = new SqlCommand();
        com1.Connection = conn1;
        if (Request.QueryString["title_id"] != null)
        {
            string title_id = Request.QueryString["title_id"].ToString();

            if (checkList(title_id))
            {
                if (!IsPostBack)
                {
                    playListFile = MapPath("../../lapUpLoad/player2/");
                    if (toList(title_id) && toHtml(title_id))
                    {
                        url = string.Format("{0}/player2/play.php?listxml={1}&config={2}&random={3}", System.Configuration.ConfigurationManager.AppSettings["php"], xmlAndHtmlName + ".xml", 1,DateTime.Now.ToFileTime());
                    }
                    else
                    {
                        Response.Write(string.Format("<script language='javascript'>alert('{0}');</script>", "播放列表生成失败！"));
                    }
                }
            }
            else
            {
                phpPage.Visible = false;
                Image1.ImageUrl = "../images/confirming.jpg";
                Image1.Visible = true;
            }


        }

    }
    protected bool toList(string title_id)
    {
        string f_topic = get_bbs_f_topic(title_id);
        if (f_topic!="false")
        {
            SqlDataReader dr = getkechengs(title_id,f_topic);
            if (toXml(dr,title_id ))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }

    }

    protected bool toXml(SqlDataReader dr,string title_id)
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
        xmlDoc.AppendChild(xmlDec);
        XmlNode playlist = xmlDoc.CreateElement("playList");
        xmlDoc.AppendChild(playlist);

        XmlElement xmlEle = xmlDoc.CreateElement("Materials");
        playlist.AppendChild(xmlEle);

        XmlNode trackList = xmlDoc.CreateElement("trackList");
        playlist.AppendChild(trackList);
        bool state = false;
        while (dr.Read())
        {
            string  id=dr["title_id"].ToString();
            if (id == title_id)
            {
                state = true;
            }
            if (state)
            {
                SqlDataReader dr1 = getReader(id);
                while (dr1.Read())
                {
                    XmlNode track = xmlDoc.CreateElement("track");
                    trackList.AppendChild(track);
                    XmlElement title = xmlDoc.CreateElement("title");
                    title.InnerText = dr1["f_trueName"].ToString();
                    track.AppendChild(title);
                    XmlElement image = xmlDoc.CreateElement("image");
                    image.InnerText = "welcome.jpg";
                    track.AppendChild(image);
                    XmlElement annotation = xmlDoc.CreateElement("annotation");
                    annotation.InnerText = dr1["f_remark"].ToString();
                    track.AppendChild(annotation);
                    XmlElement location = xmlDoc.CreateElement("location");
                    location.InnerText = Path.Combine(dr1["dirName"].ToString(), dr1["f_fileName"].ToString());
                    track.AppendChild(location);
                }
                dr1.Close();
            }
        }
        xmlAndHtmlName = DateTime.Now.ToFileTime().ToString();
        xmlEle.SetAttribute("path", xmlAndHtmlName + ".html");
        string xmlFile = playListFile + xmlAndHtmlName + ".xml";
        xmlDoc.Save(xmlFile);
        dr.Dispose();
        
        return true;
    }

    protected bool toHtml(string title_id)
    {
        string sql = "select f_content from bbs where title_id=@title_id";
        com.CommandText = sql;
        com.CommandType = CommandType.Text;
        com.Parameters.AddWithValue("@title_id", title_id);
        SqlDataReader dr = com.ExecuteReader();
        string content = "";
        if (dr.Read())
        {
            content = dr[0].ToString();
        }
        htmlName = playListFile + xmlAndHtmlName + ".html";
        FileStream fs = File.Create(htmlName);
        fs.Dispose();
        using (TextWriter html = new StreamWriter(htmlName))
        {
            html.Write(content);
        }
        return true;
    }

    bool checkList(string title_id)
    {
        SqlDataReader dr = getReader(title_id);
        bool state = true;
        if (!dr.HasRows)
        {
            state = false;
        }
        while (dr.Read())
        {
            if (dr["convertStatus"].ToString() == "" || Convert.ToInt16(dr["convertStatus"].ToString()) != 2)
            {
                state = false;
            }
        }
        dr.Dispose();
        return state;
    }
    /// <summary>
    /// 获取此小节课下的所有的视频
    /// </summary>
    /// <param name="title_id"></param>
    /// <returns></returns>
    SqlDataReader getReader(string title_id)
    {
        string sql = "select * from imgUpLoad where convertStatus=2 and title_id=@titleId order by innerOrder";
        com.CommandType = CommandType.Text;
        com.CommandText = sql;
        com.Parameters.Clear();
        com.Parameters.AddWithValue("@titleId", title_id);
        SqlDataReader dr = com.ExecuteReader();
        return dr;
    }
    /// <summary>
    /// 获得此小节课所属课程的f_topic
    /// </summary>
    /// <param name="title_id"></param>
    /// <returns></returns>
    string get_bbs_f_topic(string title_id)
    {
        string sql = "select f_topic from bbs where title_id=@titleId";
        com.CommandType = CommandType.Text;
        com.CommandText = sql;
        com.Parameters.Clear();
        com.Parameters.AddWithValue("@titleId", title_id);
        SqlDataReader dr = com.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
            string topic=dr["f_topic"].ToString();
            dr.Close();
            return topic;
        }
        else
        {
            return "false";
        }

    }
    /// <summary>
    /// 获取课程下的所有的课（大于title_id的所有后续课程）
    /// </summary>
    /// <param name="title_id"></param>
    /// <param name="f_topic"></param>
    /// <returns></returns>
    SqlDataReader getkechengs(string title_id ,string f_topic)
    {
        string sql = string.Format("select title_id from bbs where f_topic like '%{0}%'  order by f_imp desc,f_date ", f_topic);
        com1.CommandType = CommandType.Text;
        com1.CommandText = sql;
        com1.Parameters.Clear();
        com1.Parameters.AddWithValue("@titleId", title_id);
        SqlDataReader dr = com1.ExecuteReader();
        return dr;
    }
}
